<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<style>
    .pace .pace-progress {
        background: #000000; /*进度条颜色*/
        height: 3px;
    }
    .pace .pace-progress-inner {
         box-shadow: 0 0 10px #1E92FB, 0 0 5px     #1E92FB; /*阴影颜色*/
    }
    .pace .pace-activity {
        border-top-color: #808080;    /*上边框颜色*/
        border-left-color: #808080;    /*左边框颜色*/
    }
</style>



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="CTF," />





  <link rel="alternate" href="/rss2.xml" title="diao-diao-UPUP" type="application/atom+xml" />






<meta name="description" content="动态渲染页面爬取前面了解到了Ajax的分析和爬取方式，这其实也是JavaScript动态渲染页面的一种方式，通过直接分析Ajax,仍然可以借助requests或urllib来实现数据爬取 但是JavaScript的动态渲染页面不止Ajax这一种，例如有些网站的分页是由JavaScript生成的，并非是原始的HTML代码，其中也并不包含Ajax Selenium的使用Selenium是一个自动化测试">
<meta name="keywords" content="CTF">
<meta property="og:type" content="article">
<meta property="og:title" content="Python3-2020&#x2F;4&#x2F;26-周报9">
<meta property="og:url" content="http:&#x2F;&#x2F;yoursite.com&#x2F;2020&#x2F;04&#x2F;26&#x2F;Python3-2020-4-26-%E5%91%A8%E6%8A%A59&#x2F;index.html">
<meta property="og:site_name" content="diao-diao-UPUP">
<meta property="og:description" content="动态渲染页面爬取前面了解到了Ajax的分析和爬取方式，这其实也是JavaScript动态渲染页面的一种方式，通过直接分析Ajax,仍然可以借助requests或urllib来实现数据爬取 但是JavaScript的动态渲染页面不止Ajax这一种，例如有些网站的分页是由JavaScript生成的，并非是原始的HTML代码，其中也并不包含Ajax Selenium的使用Selenium是一个自动化测试">
<meta property="og:locale" content="en">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;images&#x2F;python3&#x2F;selenium0.png">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;images&#x2F;python3&#x2F;selenium1.png">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;images&#x2F;python3&#x2F;selenium2.png">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;images&#x2F;python3&#x2F;selenium3.png">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;images&#x2F;python3&#x2F;selenium4.png">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;images&#x2F;python3&#x2F;selenium5.png">
<meta property="og:updated_time" content="2020-04-27T02:14:01.606Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;images&#x2F;python3&#x2F;selenium0.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2020/04/26/Python3-2020-4-26-周报9/"/>





  <title>Python3-2020/4/26-周报9 | diao-diao-UPUP</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">diao-diao-UPUP</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">我是一只web狗</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Categories
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" target="_blank" rel="noopener" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/04/26/Python3-2020-4-26-%E5%91%A8%E6%8A%A59/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="51nd0re1">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="diao-diao-UPUP">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python3-2020/4/26-周报9</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-04-26T08:08:55+08:00">
                2020-04-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%97%A5%E5%B8%B8%E5%AD%A6%E4%B9%A0/" itemprop="url" rel="index">
                    <span itemprop="name">日常学习</span>
                  </a>
                </span>

                
                
                  , 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%97%A5%E5%B8%B8%E5%AD%A6%E4%B9%A0/Python3/" itemprop="url" rel="index">
                    <span itemprop="name">Python3</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="动态渲染页面爬取"><a href="#动态渲染页面爬取" class="headerlink" title="动态渲染页面爬取"></a>动态渲染页面爬取</h1><p>前面了解到了Ajax的分析和爬取方式，这其实也是JavaScript动态渲染页面的一种方式，通过直接分析Ajax,仍然可以借助requests或urllib来实现数据爬取</p>
<p>但是JavaScript的动态渲染页面不止Ajax这一种，例如有些网站的分页是由JavaScript生成的，并非是原始的HTML代码，其中也并不包含Ajax</p>
<h2 id="Selenium的使用"><a href="#Selenium的使用" class="headerlink" title="Selenium的使用"></a>Selenium的使用</h2><p>Selenium是一个自动化测试工具，利用它可以驱动浏览器执行指定的动作，如点击，下来等操作，同时还可以获取浏览器当前呈现的页面的源代码，做到可见即可爬</p>
<h3 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h3><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.common.by import By</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.common.keys import Keys</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.support import expected_conditions as EC</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.support.wait import WebDriverWait</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line">try:</span><br><span class="line">    browser.<span class="builtin-name">get</span>(<span class="string">"https://www.baidu.com"</span>)</span><br><span class="line">    <span class="attribute">input</span>=browser.find_element_by_id('kw')</span><br><span class="line">    input.send_keys(<span class="string">'Python'</span>)</span><br><span class="line">    input.send_keys(Keys.ENTER)</span><br><span class="line">    <span class="attribute">wait</span>=WebDriverWait(browser,10)</span><br><span class="line">    wait.until(EC.presence_of_element_located((By.ID , <span class="string">'content_left'</span>)))</span><br><span class="line">    <span class="builtin-name">print</span>(browser.current_url)</span><br><span class="line">    <span class="builtin-name">print</span>(browser.get_cookies())</span><br><span class="line">    <span class="builtin-name">print</span>(browser.page_source)</span><br><span class="line">finally:</span><br><span class="line">    browser.close()</span><br><span class="line">    </span><br><span class="line">输出结果：</span><br><span class="line">当前URL，cookies和网页源代码</span><br></pre></td></tr></table></figure>
<p>再执行上条指令后，会自动弹出一个Chrome浏览器，浏览器首先会跳转到百度，然后在搜索框中输出Python，接着跳转到搜索结果页面<br><img src="/images/python3/selenium0.png" alt="avatar"><br><img src="/images/python3/selenium1.png" alt="avatar"></p>
<p>这样我们就可以直接拿到JavaScript渲染的结果了</p>
<h3 id="声明浏览器对象"><a href="#声明浏览器对象" class="headerlink" title="声明浏览器对象"></a>声明浏览器对象</h3><p>Selenium支持非常多的浏览器，如Chrome,Firefox,Edge等，还有Android，BlackBerry等手机端浏览器，还支持无界面浏览器PhantomJS</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line"><span class="attribute">browser</span>=webdriver.Firefox()</span><br><span class="line"><span class="attribute">browser</span>=webdriver.Edge()</span><br><span class="line"><span class="attribute">browser</span>=webdriver.PhantomJS()</span><br><span class="line"><span class="attribute">browser</span>=webdriver.Safari()</span><br></pre></td></tr></table></figure>
<p>这样就完成了浏览器对象的初始化，并将其赋值为browser对象</p>
<h3 id="访问页面"><a href="#访问页面" class="headerlink" title="访问页面"></a>访问页面</h3><p>我们可以使用get()方法来请求网页，参数传URL即可<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line">browser.<span class="builtin-name">get</span>(<span class="string">'https://www.taobao.com'</span>)</span><br><span class="line"><span class="builtin-name">print</span>(browser.page_source)</span><br><span class="line">browser.close()</span><br></pre></td></tr></table></figure><br>运行后发现，弹出了Chrome浏览器并且自动访问了淘宝，然后控制台输出了淘宝页面的源代码，随后浏览器关闭</p>
<h3 id="查找结点"><a href="#查找结点" class="headerlink" title="查找结点"></a>查找结点</h3><p>selenium可以驱动浏览器完成各种操作，比如填充表单，模拟点击等。比如，我们想要完成向某个输入框输入文字的操作，需要知道这个输入框在哪里，而selenium提供了一系列查找节点的方法</p>
<h4 id="单个节点"><a href="#单个节点" class="headerlink" title="单个节点"></a>单个节点</h4><p>比如，想要从淘宝页面中提取搜索框这个节点，首先观察它的源代码<br><img src="/images/python3/selenium2.png" alt="avatar"><br>可以发现它的id是q,name也是q，此外还有许多其他属性，我们就可以以多种方式获取了<br>比如find_element_by_name()是根据name获取，find_element_by_id()是根据id获取<br>另外，还有根据XPath，CSS选择器等获取方式<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">from selenium import webdriver</span><br><span class="line"></span><br><span class="line">browser=webdriver.Chrome()</span><br><span class="line">browser.get(<span class="string">'https://www.taobao.com'</span>)</span><br><span class="line">input_first=browser.find_element_by_id(<span class="string">'q'</span>)</span><br><span class="line">input_second=browser.find_element_by_css_selector(<span class="string">'#q'</span>)</span><br><span class="line">input_third=browser.find_element_by_xpath(<span class="string">'//*[@id="q"]'</span>)</span><br><span class="line"><span class="function"><span class="title">print</span><span class="params">(input_first,input_second,input_third)</span></span></span><br><span class="line">browser.close()</span><br><span class="line"></span><br><span class="line">输出结果：</span><br><span class="line">&lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"b332cd2cb2191a08286eada1aceb4b4e"</span>, element=<span class="string">"1b3bf42c-4780-4c65-9b6f-fca9190503f4"</span>)&gt;</span><br><span class="line">&lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"b332cd2cb2191a08286eada1aceb4b4e"</span>, element=<span class="string">"1b3bf42c-4780-4c65-9b6f-fca9190503f4"</span>)&gt;</span><br><span class="line">&lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"b332cd2cb2191a08286eada1aceb4b4e"</span>, element=<span class="string">"1b3bf42c-4780-4c65-9b6f-fca9190503f4"</span>)&gt;</span><br></pre></td></tr></table></figure></p>
<p>我们发现结果一至，可以看到这三个节点都是WebElement类型<br>获取单个节点的方法：<br><figure class="highlight ceylon"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">find<span class="number">_</span>element<span class="number">_</span><span class="meta">by</span><span class="number">_</span>id</span><br><span class="line">find<span class="number">_</span>element<span class="number">_</span><span class="meta">by</span><span class="number">_n</span>ame</span><br><span class="line">find<span class="number">_</span>element<span class="number">_</span><span class="meta">by</span><span class="number">_</span>xpath</span><br><span class="line">find<span class="number">_</span>element<span class="number">_</span><span class="meta">by</span><span class="number">_</span>link<span class="number">_</span>text</span><br><span class="line">find<span class="number">_</span>element<span class="number">_</span><span class="meta">by</span><span class="number">_p</span>artial<span class="number">_</span>link<span class="number">_</span>text</span><br><span class="line">find<span class="number">_</span>element<span class="number">_</span><span class="meta">by</span><span class="number">_</span>tag<span class="number">_n</span>ame</span><br><span class="line">find<span class="number">_</span>element<span class="number">_</span><span class="meta">by</span><span class="number">_</span><span class="keyword">class</span><span class="number">_n</span>ame</span><br><span class="line">find<span class="number">_</span>element<span class="number">_</span><span class="meta">by</span><span class="number">_</span>css<span class="number">_</span>selector</span><br></pre></td></tr></table></figure><br>此外还提供了通用方法find_element()，它需要传入两个参数，查找方法By和值<br>实际就是上述方法的通用版本</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.common.<span class="keyword">by</span> <span class="keyword">import</span> <span class="keyword">By</span></span><br><span class="line"></span><br><span class="line">browser=webdriver.Chrome()</span><br><span class="line">browser.<span class="keyword">get</span>(<span class="string">'https://www.taobao.com'</span>)</span><br><span class="line">input_first=browser.find_element(<span class="keyword">By</span>.ID,<span class="string">'q'</span>)</span><br><span class="line">print(input_first)</span><br><span class="line">browser.<span class="keyword">close</span>()</span><br><span class="line"></span><br><span class="line">输出结果与上面一至</span><br></pre></td></tr></table></figure>
<h4 id="多个节点"><a href="#多个节点" class="headerlink" title="多个节点"></a>多个节点</h4><p>如果查找的目标在网页中只有一个，那么完全可以使用find_element()方法，但是如果有多个节点，就需要使用find_elements()方法了</p>
<p>比如淘宝导航条的所有条目<br><img src="/images/python3/selenium3.png" alt="avatar"></p>
<p>先查看这些条目，发现都在class为service-bd的ul节点的li节点中<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">from selenium import webdriver</span><br><span class="line"></span><br><span class="line">browser=webdriver.Chrome()</span><br><span class="line">browser.get(<span class="string">'https://www.taobao.com'</span>)</span><br><span class="line">lis=browser.find_elements_by_css_selector(<span class="string">'.service-bd li'</span>)</span><br><span class="line"><span class="function"><span class="title">print</span><span class="params">(lis)</span></span></span><br><span class="line">browser.close()</span><br><span class="line"></span><br><span class="line">输出结果：</span><br><span class="line">[&lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"7237cd9e-6812-41b2-839c-5a5ef0790077"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"cd8c7478-6486-4376-8c25-a562dad5be68"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"01ac2aac-0431-49f5-9e9b-244fb11a5b99"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"5f10b89b-f4f2-4efb-a084-3ce219e81aa2"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"b99fefe4-b5d0-42c9-84d2-068ba0738d53"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"4ce8e958-225e-480b-9e43-d0510bd6b7ee"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"c37b736b-8d99-4424-a38c-f5270bdc274c"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"a1c19196-5d1e-414b-ae4b-44ad67938651"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"387c966a-29d2-4ced-a1bf-ae11d24f3252"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"f74ecd4d-68eb-4be6-b50a-6ad5f792b9af"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"5c413df1-2c09-4a10-88ee-c27287535d6e"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"73ee7920-b2dd-44dd-b5b5-97a36b5684e1"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"5ef053b7-90a1-4a0d-b504-284d8d9ed497"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"555d8a92-90bd-4724-99ab-fcdb88397077"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"98329539-7cf1-404a-8903-d3ea72f3bb6d"</span>)&gt;, &lt;selenium<span class="selector-class">.webdriver</span><span class="selector-class">.remote</span><span class="selector-class">.webelement</span><span class="selector-class">.WebElement</span> (session=<span class="string">"cb088f704736092b306130aab2abf8f1"</span>, element=<span class="string">"df6d8c38-5f1d-4872-8a30-d6e0e1ca02ad"</span>)&gt;]</span><br></pre></td></tr></table></figure><br>这样就获取到了所有条目的源代码</p>
<p>获取多个节点<br><figure class="highlight ceylon"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">find<span class="number">_</span>elements<span class="number">_</span><span class="meta">by</span><span class="number">_</span>id</span><br><span class="line">find<span class="number">_</span>elements<span class="number">_</span><span class="meta">by</span><span class="number">_n</span>ame</span><br><span class="line">find<span class="number">_</span>elements<span class="number">_</span><span class="meta">by</span><span class="number">_</span>xpath</span><br><span class="line">find<span class="number">_</span>elementst<span class="number">_</span><span class="meta">by</span><span class="number">_</span>link<span class="number">_</span>text</span><br><span class="line">find<span class="number">_</span>elements<span class="number">_</span><span class="meta">by</span><span class="number">_p</span>artial<span class="number">_</span>link<span class="number">_</span>text</span><br><span class="line">find<span class="number">_</span>elements<span class="number">_</span><span class="meta">by</span><span class="number">_</span>tag<span class="number">_n</span>ame</span><br><span class="line">find<span class="number">_</span>elements<span class="number">_</span><span class="meta">by</span><span class="number">_</span><span class="keyword">class</span><span class="number">_n</span>ame</span><br><span class="line">find<span class="number">_</span>elementst<span class="number">_</span><span class="meta">by</span><span class="number">_</span>css<span class="number">_</span>selector</span><br></pre></td></tr></table></figure></p>
<p>同时还有通用方法<br><figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">lis=browser.find<span class="constructor">_elements(By.CSS_SELECTOR,'.<span class="params">service</span>-<span class="params">bd</span> <span class="params">li</span>')</span></span><br></pre></td></tr></table></figure></p>
<h4 id="节点交互"><a href="#节点交互" class="headerlink" title="节点交互"></a>节点交互</h4><p>我们还可以让浏览器执行一些操作，比较常见的如输入文字时用send_keys()方法，清空文字时用clear()方法，点击按钮时用click()方法<br><figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"><span class="keyword">import</span> <span class="type">time</span></span><br><span class="line"></span><br><span class="line">browser=webdriver.Chrome()</span><br><span class="line">browser.<span class="keyword">get</span>(<span class="string">'https://www.taobao.com'</span>)</span><br><span class="line">input=browser.find_element_by_id(<span class="string">'q'</span>)</span><br><span class="line"><span class="keyword">input</span>.send_keys(<span class="string">'iphone'</span>)</span><br><span class="line"><span class="type">time</span>.sleep(<span class="number">1</span>)</span><br><span class="line"><span class="keyword">input</span>.clear()</span><br><span class="line"><span class="keyword">input</span>.send_keys(<span class="string">'ipad'</span>)</span><br><span class="line">button=browser.find_element_by_class_name(<span class="string">'btn-search'</span>)</span><br><span class="line">button.click()</span><br></pre></td></tr></table></figure><br>这里首先驱动浏览器打开淘宝，然后用find_element_by_id()方法获取输入框，然后用send_keys()方法输入iphone文字，等待一秒后用clear()方法清空输入框，再次调用send_keys()方法输入ipad文字，之后再用find_element_by_class_name()方法获取搜索按钮，最后调用click()方法完成搜索动作</p>
<p>更多交互请参考文档：<br>中文文档：<br><a href="https://python-selenium-zh.readthedocs.io/zh_CN/latest/" target="_blank" rel="noopener">https://python-selenium-zh.readthedocs.io/zh_CN/latest/</a><br>官方文档：<br><a href="https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" target="_blank" rel="noopener">https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement</a></p>
<h4 id="动作链"><a href="#动作链" class="headerlink" title="动作链"></a>动作链</h4><p>在上面的实例中，发现一些交互动作都是针对某个节点执行的。比如，对于输入框，我们就是调用它的输入文字和清空文字方法，对于按钮，就调用它的点击方法.其次，还有另外一些操作，它们没有特定的执行对象，比如鼠标拖拽，键盘按键等</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver <span class="keyword">import</span> ActionChains</span><br><span class="line"></span><br><span class="line">browser=webdriver.Chrome()</span><br><span class="line">url="http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"</span><br><span class="line">browser.<span class="keyword">get</span>(url)</span><br><span class="line">browser.switch_to.frame(<span class="string">'iframeResult'</span>)</span><br><span class="line">source = browser.find_element_by_css_selector(<span class="string">'#draggable'</span>)</span><br><span class="line">target = browser.find_element_by_css_selector(<span class="string">'#droppable'</span>)</span><br><span class="line">actions = ActionChains(browser)</span><br><span class="line">actions.drag_and_drop(source , target)</span><br><span class="line">actions.<span class="keyword">perform</span>()</span><br></pre></td></tr></table></figure>
<p>运行后会将小方块拖拽到大方块中<br><img src="/images/python3/selenium4.png" alt="avatar"></p>
<p>更多动作链操作请参考文档：<br>中文文档：<br><a href="https://python-selenium-zh.readthedocs.io/zh_CN/latest/" target="_blank" rel="noopener">https://python-selenium-zh.readthedocs.io/zh_CN/latest/</a><br>官方文档：<br><a href="https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" target="_blank" rel="noopener">https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement</a></p>
<h4 id="执行JavaScript"><a href="#执行JavaScript" class="headerlink" title="执行JavaScript"></a>执行JavaScript</h4><p>对于某些操作，Selenium API并没有提供。比如，下拉进度条，它可以直接模拟运行JavaScript，此时使用execute_script()方法即可实现<br><figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">from selenium import webdriver</span><br><span class="line"></span><br><span class="line">browser=webdriver.<span class="constructor">Chrome()</span></span><br><span class="line">browser.get(<span class="string">"https://www.zhihu.com/explore"</span>)</span><br><span class="line">browser.execute<span class="constructor">_script('<span class="params">window</span>.<span class="params">scrollTo</span>(0,<span class="params">document</span>.<span class="params">body</span>.<span class="params">scrollHeight</span>)</span>')</span><br><span class="line">browser.execute<span class="constructor">_script('<span class="params">alert</span>(<span class="string">"To Bottom"</span>)</span>')</span><br></pre></td></tr></table></figure><br><img src="/images/python3/selenium5.png" alt="avatar"><br>这里就利用execute_script()方法将进度条下拉到最底部，然后弹出alert提示框</p>
<p>所以说有了这个方法，基本上API没有提供的所有功能都可以用执行JavaScript的方式来实现了</p>
<h4 id="获取节点信息"><a href="#获取节点信息" class="headerlink" title="获取节点信息"></a>获取节点信息</h4><p>前面通过Beautiful Soup,pyquery等提取信息</p>
<p>Selenium中提供了选择节点的方法，返回的是WebElement类型，那么它也有相关的方法和属性来直接提取节点信息，如属性，文本等。这样的话，我们就可以不用通过解析源代码来提取信息了</p>
<h5 id="获取属性"><a href="#获取属性" class="headerlink" title="获取属性"></a>获取属性</h5><p>我们可以通过get_attribute()方法来获取节点的属性，前提是先选中这个节点<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line"><span class="attribute">url</span>=<span class="string">'https://www.zhihu.com/explore'</span></span><br><span class="line">browser.<span class="builtin-name">get</span>(url)</span><br><span class="line"><span class="attribute">logo</span>=browser.find_element_by_id('zh-top-link-logo')</span><br><span class="line"><span class="builtin-name">print</span>(logo)</span><br><span class="line"><span class="builtin-name">print</span>(logo.get_attribute(<span class="string">'class'</span>))</span><br></pre></td></tr></table></figure><br>通过get_attribute()方法，然后传入想要获取的属性名，就可以得到它的值了</p>
<h5 id="获取文本值"><a href="#获取文本值" class="headerlink" title="获取文本值"></a>获取文本值</h5><p>每个WebElement节点都有text属性，直接调用这个属性就可以得到节点内部的文本信息，这相当于Beautiful Soup中的get_text()方法，pyquery的text()方法<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line"><span class="attribute">url</span>=<span class="string">'https://www.zhihu.com/explore'</span></span><br><span class="line">browser.<span class="builtin-name">get</span>(url)</span><br><span class="line"><span class="attribute">input</span>=browser.find_element_by_class_name('ExploreHomePage-ContentSection-header')</span><br><span class="line"><span class="builtin-name">print</span>(input.text)</span><br><span class="line"></span><br><span class="line">输出结果：</span><br><span class="line">最新专题</span><br></pre></td></tr></table></figure><br>这样就获得了最新专题节点的内容</p>
<h5 id="获取id-位置，标签名和大小"><a href="#获取id-位置，标签名和大小" class="headerlink" title="获取id,位置，标签名和大小"></a>获取id,位置，标签名和大小</h5><p>WebElement节点还有一些其他的属性，比如id属性可以获取节点的id,location属性可以获取该节点在页面中的相对位置，tag_name属性可以获取标签名称，size属性可以获取节点的大小，也就是宽高<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line"><span class="attribute">url</span>=<span class="string">'https://www.zhihu.com/explore'</span></span><br><span class="line">browser.<span class="builtin-name">get</span>(url)</span><br><span class="line"><span class="attribute">input</span>=browser.find_element_by_class_name('ExploreHomePage-ContentSection-header')</span><br><span class="line"><span class="builtin-name">print</span>(input.text)</span><br><span class="line"><span class="builtin-name">print</span>(input.id)</span><br><span class="line"><span class="builtin-name">print</span>(input.location)</span><br><span class="line"><span class="builtin-name">print</span>(input.tag_name)</span><br><span class="line"><span class="builtin-name">print</span>(input.size)</span><br><span class="line"></span><br><span class="line">输出结果：</span><br><span class="line">最新专题</span><br><span class="line">b74d780d-b4f2-4a35-9221-cb40a5e48902</span><br><span class="line">&#123;<span class="string">'x'</span>: 10, <span class="string">'y'</span>: 84&#125;</span><br><span class="line">div</span><br><span class="line">&#123;<span class="string">'height'</span>: 36, <span class="string">'width'</span>: 1000&#125;</span><br></pre></td></tr></table></figure><br>这样就获取到了id,位置，标签名和大小</p>
<h4 id="切换Frame"><a href="#切换Frame" class="headerlink" title="切换Frame"></a>切换Frame</h4><p>网页中有一个节点叫做iframe，也就是子Frame，相当于页面中的子页面，它的结构和外部网页的结构完全一致。Selenium打开页面后，它默认是在父级Frame里操作，而此时如果页面中还有子Frame，它是不能获取到子Frame里面的节点的，这时就需要switch_to.frame()方法来切换Frame</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">import time</span><br><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"><span class="keyword">from</span> selenium.common.exceptions import NoSuchElementException</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line"><span class="attribute">url</span>=<span class="string">'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'</span></span><br><span class="line">browser.<span class="builtin-name">get</span>(url)</span><br><span class="line">browser.switch_to.frame(<span class="string">'iframeResult'</span>)</span><br><span class="line">try:</span><br><span class="line">    <span class="attribute">logo</span>=browser.find_element_by_class_name('logo')</span><br><span class="line">except NoSuchElementException:</span><br><span class="line">    <span class="builtin-name">print</span>(<span class="string">"NO LOGO"</span>)</span><br><span class="line">browser.switch_to.parent_frame()</span><br><span class="line"><span class="attribute">logo</span>=browser.find_element_by_class_name('logo')</span><br><span class="line"><span class="builtin-name">print</span>(logo)</span><br><span class="line"><span class="builtin-name">print</span>(logo.text)</span><br><span class="line"></span><br><span class="line">输出结果：</span><br><span class="line"><span class="literal">NO</span> LOGO</span><br><span class="line">&lt;selenium.webdriver.remote.webelement.WebElement (<span class="attribute">session</span>=<span class="string">"74a6a23d440b28de1d52cee1269b0ca6"</span>, <span class="attribute">element</span>=<span class="string">"909ba7c7-467d-4bb7-86aa-3df9d4981362"</span>)&gt;</span><br><span class="line">RUNOOB.COM</span><br></pre></td></tr></table></figure>
<p>首先通过switch_to.frame()方法切换到子Frame里面，然后尝试获取子Frame里的logo节点，如果找不到的话，就会抛出NoSuchElementException异常。接下来，重新切换到父级Frame,再次重新获取节点，就可以成功捕获了</p>
<h4 id="延时等待"><a href="#延时等待" class="headerlink" title="延时等待"></a>延时等待</h4><p>get()方法会在网页框架加载结束后结束执行，此时如果获取page_source,可能并不是浏览器完全加载完成的页面，如果某些页面有额外的Ajax请求，我们在网页源代码中也不一定能获取到。所以，这里需要延时等待一定时间，确保节点已经加载出来</p>
<h5 id="隐式等待"><a href="#隐式等待" class="headerlink" title="隐式等待"></a>隐式等待</h5><p>当使用隐式等待执行测试的时候，如果selenium没有在DOM中找到节点，将继续等待，超出设定时间后，则抛出找不到节点的异常。换句话说，当查找节点而节点并没有立即出现的时候，隐式等待将等待一段时间再查找DOM，默认事件为0<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line">browser.implicitly_wait(10)</span><br><span class="line">browser.<span class="builtin-name">get</span>(<span class="string">'https://www.zhihu.com/explore'</span>)</span><br><span class="line"><span class="attribute">input</span>=browser.find_element_by_class_name('ExploreHomePage-ContentSection-header')</span><br><span class="line"><span class="builtin-name">print</span>(input)</span><br></pre></td></tr></table></figure><br>这里使用了隐式等待implicitly_wait()</p>
<h5 id="显式等待"><a href="#显式等待" class="headerlink" title="显式等待"></a>显式等待</h5><p>隐式等待的效果其实并没有那么好，因为我们只规定了一个固定时间，而页面加载时间还会受到网络条件的影响</p>
<p>这里还有一种更合适的显式等待方法，它指定要查找的节点，然后指定一个最长等待时间。如果在规定时间内加载出来了节点，就返回查找的节点，反之</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.common.by import By</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.support.ui import WebDriverWait</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.support import expected_conditions as EC</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line">browser.<span class="builtin-name">get</span>(<span class="string">'https://www.taobao.com'</span>)</span><br><span class="line"><span class="attribute">wait</span>=WebDriverWait(browser,10)</span><br><span class="line"><span class="attribute">input</span>=wait.until(EC.presence_of_element_located((By.ID,'q')))</span><br><span class="line"><span class="attribute">button</span>=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.btn-search')))</span><br><span class="line"><span class="builtin-name">print</span>(input,button)</span><br><span class="line"></span><br><span class="line">输出结果：</span><br><span class="line">&lt;selenium.webdriver.remote.webelement.WebElement (<span class="attribute">session</span>=<span class="string">"8ed44db593e504803b1e1bbdaa40096f"</span>, <span class="attribute">element</span>=<span class="string">"2e6789ed-7862-419b-adca-2cea31a3d3c9"</span>)&gt; &lt;selenium.webdriver.remote.webelement.WebElement (<span class="attribute">session</span>=<span class="string">"8ed44db593e504803b1e1bbdaa40096f"</span>, <span class="attribute">element</span>=<span class="string">"4d2571b6-fd8d-47e2-8490-f6fddf96959b"</span>)&gt;</span><br></pre></td></tr></table></figure>
<p>首先引入WebDriverWait这个对象，指定最长等待时间，然后调用它的until()方法，传入要等待条件expected_conditions。比如，这里传入了presence_of_element_located这个条件，代表节点出现的意思，其参数是节点的定位元组，也就是ID为q的节点搜索框</p>
<p>这样可以做到的效果就是，在10秒内如果ID为q的节点成功加载出来，就返回该节点；如果超过10秒还没有加载出来，就抛出异常。</p>
<p>对于按钮，可以更改一下等待条件，比如改为element_to_be_clickable，也就是可点击，所以查找按钮时查找CSS选择器为.btn-search的按钮，如果10秒内它是可点击的，也就是成功加载出来了，就返回这个按钮节点，反之</p>
<p>更多操作请参考文档<br>中文文档：<br><a href="https://python-selenium-zh.readthedocs.io/zh_CN/latest/" target="_blank" rel="noopener">https://python-selenium-zh.readthedocs.io/zh_CN/latest/</a><br>官方文档：<br><a href="https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" target="_blank" rel="noopener">https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement</a></p>
<h4 id="前进和后退"><a href="#前进和后退" class="headerlink" title="前进和后退"></a>前进和后退</h4><p>平时使用浏览器时都有前进和后退功能，selenium也可以完成这个操作，它使用back()方法后退，使用forward()方法前进。<br><figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="type">time</span></span><br><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"></span><br><span class="line">browser=webdriver.Chrome()</span><br><span class="line">browser.<span class="keyword">get</span>(<span class="string">'https://www.baidu.com'</span>)</span><br><span class="line">browser.<span class="keyword">get</span>(<span class="string">'https://www.taobao.com'</span>)</span><br><span class="line">browser.<span class="keyword">get</span>(<span class="string">'https://www.python.org'</span>)</span><br><span class="line">browser.back()</span><br><span class="line"><span class="type">time</span>.sleep(<span class="number">1</span>)</span><br><span class="line">browser.forward()</span><br><span class="line">browser.<span class="keyword">close</span>()</span><br></pre></td></tr></table></figure><br>这样我们连续访问3个页面，然后调用back方法回到第二个页面，接下来再调用forward()方法又可以前进到第三个页面</p>
<h4 id="cookies"><a href="#cookies" class="headerlink" title="cookies"></a>cookies</h4><p>使用selenium，还可以方便地对Cookies进行操作，例如获取，添加，删除Cookies等<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line">browser.<span class="builtin-name">get</span>(<span class="string">'https://www.zhihu.com/explore'</span>)</span><br><span class="line"><span class="builtin-name">print</span>(browser.get_cookies())</span><br><span class="line">browser.add_cookie(&#123;<span class="string">'name'</span>:<span class="string">'name'</span>,<span class="string">'domain'</span>:<span class="string">'www.zhihu.com'</span>,<span class="string">'value'</span>:<span class="string">'germey'</span>&#125;)</span><br><span class="line"><span class="builtin-name">print</span>(browser.get_cookies())</span><br><span class="line">browser.delete_all_cookies()</span><br><span class="line"><span class="builtin-name">print</span>(browser.get_cookies())</span><br><span class="line"></span><br><span class="line">输出结果：</span><br><span class="line">[&#123;<span class="string">'domain'</span>: <span class="string">'www.zhihu.com'</span>, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'KLBRSID'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'cdfcc1d45d024a211bb7144f66bda2cf|1587952898|1587952896'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'expiry'</span>: 1619488898, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'1587952898'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'1587952898'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'expiry'</span>: 1682560896.073367, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'d_c0'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'"AIBbIT5rLhGPTpMVZJCLnmYZXYPvh8AXzpM=|1587952896"'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'www.zhihu.com'</span>, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'SESSIONID'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'Ns5jG8TIaSE1aAjeOzckOayn6V6nDAubFTUf1DfCC2H'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'_xsrf'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'6e9342c2-b0fd-4474-9099-193fef3e5595'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'expiry'</span>: 1651024896.073016, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'_zap'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'2dbb5fb5-9f25-44ae-ac01-5183941f56df'</span>&#125;]</span><br><span class="line"></span><br><span class="line">[&#123;<span class="string">'domain'</span>: <span class="string">'.www.zhihu.com'</span>, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'name'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">True</span>, <span class="string">'value'</span>: <span class="string">'germey'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'www.zhihu.com'</span>, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'KLBRSID'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'cdfcc1d45d024a211bb7144f66bda2cf|1587952898|1587952896'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'expiry'</span>: 1619488898, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'1587952898'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'1587952898'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'expiry'</span>: 1682560896.073367, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'d_c0'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'"AIBbIT5rLhGPTpMVZJCLnmYZXYPvh8AXzpM=|1587952896"'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'www.zhihu.com'</span>, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'SESSIONID'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'Ns5jG8TIaSE1aAjeOzckOayn6V6nDAubFTUf1DfCC2H'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'_xsrf'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'6e9342c2-b0fd-4474-9099-193fef3e5595'</span>&#125;, &#123;<span class="string">'domain'</span>: <span class="string">'.zhihu.com'</span>, <span class="string">'expiry'</span>: 1651024896.073016, <span class="string">'httpOnly'</span>: <span class="literal">False</span>, <span class="string">'name'</span>: <span class="string">'_zap'</span>, <span class="string">'path'</span>: <span class="string">'/'</span>, <span class="string">'secure'</span>: <span class="literal">False</span>, <span class="string">'value'</span>: <span class="string">'2dbb5fb5-9f25-44ae-ac01-5183941f56df'</span>&#125;]</span><br><span class="line"></span><br><span class="line">[]</span><br></pre></td></tr></table></figure><br>可以看到我们添加的cookie被添加到了cookies中</p>
<h4 id="选项卡管理"><a href="#选项卡管理" class="headerlink" title="选项卡管理"></a>选项卡管理</h4><p>访问网页的时候，会开启一个个选项卡。在selenium中，我们可以对选项卡进行操作<br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">import time</span><br><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"></span><br><span class="line"><span class="attribute">browser</span>=webdriver.Chrome()</span><br><span class="line">browser.<span class="builtin-name">get</span>(<span class="string">'https://www.baidu.com'</span>)</span><br><span class="line">browser.execute_script(<span class="string">'window.open()'</span>)</span><br><span class="line"><span class="builtin-name">print</span>(browser.window_handles)</span><br><span class="line">browser.switch_to.window(browser.window_handles[1])</span><br><span class="line">browser.<span class="builtin-name">get</span>(<span class="string">'https://www.taobao.com'</span>)</span><br><span class="line">time.sleep(1)</span><br><span class="line">browser.switch_to.window(browser.window_handles[0])</span><br><span class="line">browser.<span class="builtin-name">get</span>(<span class="string">'https://python.org'</span>)</span><br></pre></td></tr></table></figure><br>先访问了百度，然后调用了execute_script()方法，这里传入window.open()这个JavaScript语句开启一个选项卡。然后用windows_handles属性获取当前开启地所有选项卡，返回的是选项卡的代码列表。想要切换，只需要使用switch_to.window()方法，其中是选项卡的代号即可。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>1.安装selenium之后，还需要根据浏览器的不同，安装对应的webdriver，例如Chrome的webdriver</p>
<p>2.webdriver需要放在浏览器的根目录中，并且在环境变量中引入，如果在管理员模式下cmd中，输入对应webdriver的名字，有正常显示就表示环境变量成功</p>
<p>3.如果需要通过python来对浏览器进行操作，还需要将对应的webdriver放入到python的根目录下</p>
<p>4.selenium可以操作浏览器自动完成一些操作，所以需要注意一些危险操作，以免操作信息泄露</p>
<p>5.selenium功能强大，可以使用动作链和节点交互功能完成一系列重复性操作，例如抢课等</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/CTF/" rel="tag"># CTF</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/04/18/Python3-2020-4-18-%E5%91%A8%E6%8A%A58/" rel="next" title="Python3-2020/4/18-周报8">
                <i class="fa fa-chevron-left"></i> Python3-2020/4/18-周报8
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/05/02/Python3-2020-5-1-%E5%91%A8%E6%8A%A510/" rel="prev" title="Python3-2020/5/1-周报10">
                Python3-2020/5/1-周报10 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="51nd0re1" />
            
              <p class="site-author-name" itemprop="name">51nd0re1</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/rss2.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/diao-diao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:302684932@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://l0x1c.github.io/" title="L0x1c" target="_blank">L0x1c</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://15h3na0.xyz/" title="15h3na0" target="_blank">15h3na0</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://p3rh4ps.top/" title="p3rh4ps" target="_blank">p3rh4ps</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.cnblogs.com/yesec/" title="yesec" target="_blank">yesec</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://ch4ser-go.github.io/" title="ch4ser" target="_blank">ch4ser</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ggb0n.cool/" title="ggb0n" target="_blank">ggb0n</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://github.mrkaixin.computer/" title="mrkaixin" target="_blank">mrkaixin</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://imagin.vip/" title="imagin" target="_blank">imagin</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#动态渲染页面爬取"><span class="nav-number">1.</span> <span class="nav-text">动态渲染页面爬取</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Selenium的使用"><span class="nav-number">1.1.</span> <span class="nav-text">Selenium的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#基本使用"><span class="nav-number">1.1.1.</span> <span class="nav-text">基本使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#声明浏览器对象"><span class="nav-number">1.1.2.</span> <span class="nav-text">声明浏览器对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#访问页面"><span class="nav-number">1.1.3.</span> <span class="nav-text">访问页面</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查找结点"><span class="nav-number">1.1.4.</span> <span class="nav-text">查找结点</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#单个节点"><span class="nav-number">1.1.4.1.</span> <span class="nav-text">单个节点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#多个节点"><span class="nav-number">1.1.4.2.</span> <span class="nav-text">多个节点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#节点交互"><span class="nav-number">1.1.4.3.</span> <span class="nav-text">节点交互</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#动作链"><span class="nav-number">1.1.4.4.</span> <span class="nav-text">动作链</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#执行JavaScript"><span class="nav-number">1.1.4.5.</span> <span class="nav-text">执行JavaScript</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取节点信息"><span class="nav-number">1.1.4.6.</span> <span class="nav-text">获取节点信息</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#获取属性"><span class="nav-number">1.1.4.6.1.</span> <span class="nav-text">获取属性</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#获取文本值"><span class="nav-number">1.1.4.6.2.</span> <span class="nav-text">获取文本值</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#获取id-位置，标签名和大小"><span class="nav-number">1.1.4.6.3.</span> <span class="nav-text">获取id,位置，标签名和大小</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#切换Frame"><span class="nav-number">1.1.4.7.</span> <span class="nav-text">切换Frame</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#延时等待"><span class="nav-number">1.1.4.8.</span> <span class="nav-text">延时等待</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#隐式等待"><span class="nav-number">1.1.4.8.1.</span> <span class="nav-text">隐式等待</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#显式等待"><span class="nav-number">1.1.4.8.2.</span> <span class="nav-text">显式等待</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#前进和后退"><span class="nav-number">1.1.4.9.</span> <span class="nav-text">前进和后退</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#cookies"><span class="nav-number">1.1.4.10.</span> <span class="nav-text">cookies</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#选项卡管理"><span class="nav-number">1.1.4.11.</span> <span class="nav-text">选项卡管理</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">2.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">51nd0re1</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  


  

  

  
  <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>

</body>
</html>
